// pages/addressAdd/addressAdd.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    show: false,
    tabFlag: 0,
    toView: '',
    id: '', // 修改地址id
    name: '', // 姓名
    tel: '', // 电话
    addressDetail: '', // 详细收货地址
    // postalCode: '', // 邮政编码
    area: '', // 地区
    isDefault: 1, // 是否默认
    tabList: ['请选择', '请选择', '请选择'],
    oldTabList: ['请选择', '请选择', '请选择'],
    cityList: [],
    scrollTop: 100
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log('==== options ====', options)
    let that = this

    if (options.id) {
      let res = wx.getStorageSync('addressItem')
      console.log('==== addressItem ====', res)

      let provincList = await wx.promiseGet("/api/region/list?pid=0")
      let cityList = await wx.promiseGet(`/api/region/list?pid=${res.province}`)
      let countyList = await wx.promiseGet(`/api/region/list?pid=${res.city}`)

      let tabList = []
      tabList[0] = provincList.data.filter(item => item.id == res.province)[0]
      tabList[1] = cityList.data.filter(item => item.id == res.city)[0]
      tabList[2] = countyList.data.filter(item => item.id == res.county)[0]
      tabList[0]._id = '_' + tabList[0].id
      tabList[1]._id = '_' + tabList[1].id
      tabList[2]._id = '_' + tabList[2].id

      that.setData({
        name: res.name,
        tel: res.tel,
        area: res.provinceName + "/" + res.cityName + "/" + res.countyName,
        addressDetail: res.addressDetail,
        // postalCode: res.postalCode,
        toView: '_' + res.province,
        id: options.id,
        isDefault: res.isDefault,
        oldTabList: JSON.parse(JSON.stringify(tabList)),
        tabList: JSON.parse(JSON.stringify(tabList))
      })
    }

    let province_list = await wx.promiseGet("/api/region/list?pid=0")
    province_list.data.map(item => item._id = '_' + item.id)
    console.log('=== 地址列表 ====', province_list)
    this.setData({
      cityList: province_list.data,
      toView: this.data.toView
    })
  },

  // 选择省市区
  choose(e) {
    this.setData({
      [`tabList[${this.data.tabFlag}]`]: e.target.dataset.item,
      cityList: []
    })
    if (this.data.tabFlag == 2) {
      let area = ''
      this.data.tabList.forEach((item, index) => {
        area += item.name + `${index == 2 ?'': '/'}`
      })
      this.setData({
        tabFlag: 0,
        area
      })
      this.onClose()
      this.getCityList(0)
    } else {
      this.setData({
        tabFlag: ++this.data.tabFlag
      })
      this.getCityList(e.target.dataset.item.id)
    }
  },

  // 获取省市区
  getCityList(id) {
    wx.get("/api/region/list?pid=" + id, res => {
      console.log('==== detail ===', res)
      res.data.map(item => item._id = '_' + item.id)
      this.setData({
        cityList: res.data
      })
      let flag = this.data.cityList.filter(item => item._id == this.data.tabList[this.data.tabFlag]._id).length != 0
      if (this.data.tabList[this.data.tabFlag]._id && flag) {
        this.setData({
          toView: this.data.tabList[this.data.tabFlag]._id
        })
      } else {
        this.setData({
          toView: this.data.cityList[0]._id
        })
      }
    }, fail => {})
  },

  // 数据
  bindKeyInput: function (e) {
    console.info(e.detail.value)
    if (e.target.dataset.name == 'tel') {
      var reg = /^1[0-9]{0,10}$/ 
      console.info(reg.test(e.detail.value))
      if(!reg.test(e.detail.value)) {
        this.setData({
          tel : e.detail.value.slice(0, -1)
        })
        return
      }
    }
    this.setData({
      [e.target.dataset.name]: e.detail.value
    })
  },

  // 设置默认地址
  setDefault() {
    if (this.data.isDefault == 1) {
      this.setData({
        isDefault: 0
      })
    } else {
      this.setData({
        isDefault: 1
      })
    }
  },

  // 添加地址
  addAddress() {
    var reg = /^1\d{10}$/ 
    if (!reg.test(this.data.tel)) {
      wx.showModal({
        title: '温馨提示',
        content: '手机号码格式有误，请重新输入',
        showCancel: false
      })
      return
    }
    let params = {
      name: this.data.name,
      tel: this.data.tel,
      addressDetail: this.data.addressDetail,
      postalCode: this.data.postalCode,
      province: this.data.tabList[0].id,
      city: this.data.tabList[1].id,
      county: this.data.tabList[2].id,
      areaCode: this.data.tabList[2].code,
      isDefault: this.data.isDefault
    }
    this.data.id ? params.id = this.data.id : ''
    console.log('=== 添加地址上传 ====', params)
    wx.showLoading({
      mask: true
    })
    wx.post("/api/address", params, res => {
      wx.hideLoading()
      console.log('==== address ===', res)
      if (res.code == 200) {
        wx.showToast({
          title: `地址${this.data.id?'修改':'添加'}成功`,
          icon: 'none',
          duration: 1000
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000)

      }
    }, fail => {})
  },

  // 打开弹框
  showPopup() {
    this.setData({
      show: true
    });
    if (this.data.id) { // 修改地址 第一次打开地址弹框 不能复现到具体位置
      setTimeout(() => {
        this.setData({
          toView: this.data.toView
        })
      }, 200)
    }
  },

  // 关闭弹框
  onClose() {
    this.setData({
      show: false
    });
    if (this.data.tabFlag == 0) {
      this.setData({
        oldTabList: JSON.parse(JSON.stringify(this.data.tabList))
      });
    } else {
      this.setData({
        tabList: JSON.parse(JSON.stringify(this.data.oldTabList)),
        tabFlag: 0
      });
      this.getCityList(0)
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})